<template>
  <el-dialog
    title="添加分类"
    :visible="dialogVisible"
    width="30%"
    :before-close="handleCloseAdd"
    top="15vh"
    @close="handleCloseAdd"
  >
    <el-form ref="catFormRef" :model="catForm" label-width="80px">
      <el-form-item label="分类名称">
        <el-input v-model="catForm.cat_name"></el-input>
      </el-form-item>
      <el-form-item label="父级分类">
        <!-- 级联选择器开始 -->
        <el-cascader
          expand-trigger="hover"
          :options="options"
          :props="cascaderProps"
          v-model="selectedOptions"
          @change="handleChange"
          clearable
        >
        </el-cascader>
        <!-- 级联选择器结束 -->
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCloseAdd">取 消</el-button>
      <el-button type="primary" @click="defineBtn"> 确 定 </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { request } from "@/utils/axios.js";

export default {
  components: {},
  props: ["dialogVisible"],
  data() {
    return {
      // 表单数据
      catForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      options: [],
      // 级联选择器的配置
      cascaderProps: {
        label: "cat_name",
        children: "children",
        value: "cat_id",
      },
      selectedOptions: [],
    };
  },
  watch: {},
  computed: {},
  methods: {
    handleCloseAdd() {
      this.$refs.catFormRef.resetFields();
      this.selectedOptions = [];
      this.catForm.cat_level = 0;
      this.catForm.cat_pid = 0;
      this.$emit("closeDialog");
    },
    async getData() {
      const { data: ret } = await request.get("categories", {
        params: {
          type: 2,
        },
      });
      this.options = ret.data;
    },
    handleChange() {
      console.log(this.selectedOptions);
      if (this.selectedOptions.length > 0) {
        this.catForm.cat_pid =
          this.selectedOptions[this.selectedOptions.length - 1];
        this.catForm.cat_level = this.selectedOptions.length;
      } else {
        this.catForm.cat_pid = 0;
        this.catForm.cat_level = 0;
      }
    },
    async defineBtn() {
      // 创建分类
      const { data: ret } = await request.post("categories", this.catForm);
      console.log(ret);
      this.handleCloseAdd();
      this.$parent.getData();
    },
  },
  created() {},
  mounted() {},
};
</script>
<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>